import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { DataReportService } from '../../data-report.service';
import { FetchService } from '../../../../core/net/fetch.service';
import * as _ from 'lodash';
import { UploadXHRArgs } from 'ng-zorro-antd/upload';
import { NzInputDirective, NzMessageService, NzModalService } from 'ng-zorro-antd';
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-monthly-report',
    templateUrl: './monthly-report.component.html',
    styleUrls: ['./monthly-report.component.scss']
})
export class MonthlyReportComponent implements OnInit {
    reportType: string = '3';
    searchForm: FormGroup;
    listOfControl: { id: string; controlInstance: string } = null;
    yearList = [];
    monthlyTableData = [];
    yearlyTableData = [];

    //  月度上报表格模板
    monthlyHeadArr = [
        '计划引水量',
        '实际引水量',
        '区间补水量',
        '比计划超节情况',
        '支（斗）口计划配水量',
        '支（斗）口实际配水量',
        '自用水量',
        '干渠退水',
        '渠道利用系数',
        '商品率（%）'
    ];
    monthlyKeyArr = [
        'officeName',
        'planWatDiv',
        'planWatDivTotal',
        'actWatDiv',
        'actWatDivTotal',
        'intWatSup',
        'intWatSupTotal',
        'overWat',
        'overWatPer',
        'overWatTotal',
        'overWatTotalPer',
        'planWatDist',
        'planWatDistTotal',
        'actWatDist',
        'actWatDistTotal',
        'watConsum',
        'watConsumTotal',
        'canDewat',
        'canDewatTotal',
        'useFactor',
        'useFactorTotal',
        'commoRate',
        'commoRateTotal'
    ];

    //  年度 灌季度上报表格模板
    yearlyKeyArr = [
        'officeName',
        'planWatDiv',
        'actWatDiv',
        'intWatSup',
        'overWat',
        'overWatPer',
        'planWatDist',
        'actWatDist',
        'watConsum',
        'canDewat',
        'useFactor',
        'commoRate'
    ];
    areaHeadArr = [];
    resDataCache = {};
    areaTableData = [];
    yearAreaTableData = [];
    modalTitle: string = '所段引水数据上报';
    modalShow: boolean = false;
    modalReportType: string = '3';
    modalForm: FormGroup;
    listOfModalControl: { id: string; controlInstance: string } = null;
    modalTableData = [];
    modalTableHead = [
        '计划引水量',
        '实际引水量',
        '区间补水量',
        '支（斗）口计划配水量',
        '支（斗）口实际配水量',
        '自用水量',
        '干渠退水'
    ];
    modalKeyArr = [
        'planWatDiv',
        'actWatDiv',
        'intWatSup',
        'planWatDist',
        'actWatDist',
        'watConsum',
        'canDewat'
    ];
    uploadUrl = `${(window as any).environment.apiBaseUrl}muw/wrsMuwMReport/import`;
    // uploading = false;
    // fileList = [];
    isUseWaterTableEditable = false;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};
    yearEditCache: { [key: string]: { edit: boolean; data: any } } = {};

    modalEditCache: { [key: string]: { edit: boolean; data: any } } = {};

    isGhMng = false;    //  是否为固海管理处
    radioValue = 'GHYS';

    @ViewChild(NzInputDirective, {read: ElementRef}) inputElement: ElementRef;

    constructor(
        private dataReportService: DataReportService,
        private fetchService: FetchService,
        private message: NzMessageService,
        private fb: FormBuilder,
        private http: HttpClient,
        private modal: NzModalService
    ) {
        this.yearList = this.dataReportService.getLatestYearList(5);
    }

    ngOnInit() {
        const date = new Date();
        this.searchForm = this.fb.group({
            type: ['3'],
            year: [date.getFullYear()]
        });
        this.modalForm = this.fb.group({
            type: ['3'],
            year: [date.getFullYear()]
        });
        this.getGridData();
    }

    updateEditCache(): void {
        this.areaTableData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: {...item}
            };
        });
    }

    updateYearAreaEditCache(): void {
        this.yearAreaTableData.forEach(item => {
            this.yearEditCache[item.id] = {
                edit: false,
                data: {...item}
            };
        });
    }

    /**
     * 更新填报弹窗内表格缓存数据
     */
    updateModalEditCache(): void {
        this.modalTableData.forEach(item => {
            this.modalEditCache[item.id] = {
                edit: true,
                data: {...item}
            };
        });
    }

    startEdit(type): void {
        this.isUseWaterTableEditable = true;
        if (type === 1) {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = true;
            });
        } else {
            Object.keys(this.yearEditCache).forEach(key => {
                this.yearEditCache[key].edit = true;
            });
        }
    }

    startYearEdit(): void {
        Object.keys(this.yearEditCache).forEach(id => {
            this.yearEditCache[id].edit = true;
        });
        // this.yearEditCache[id].edit = true;
        // this.yearEditId = id;
    }

    cancelEdit(type): void {
        this.isUseWaterTableEditable = false;
        if (type === 1) {
            this.updateEditCache();
        } else {
            this.updateYearAreaEditCache();
        }
    }

    startModalEdit(): void {
        Object.keys(this.modalEditCache).forEach(key => {
            this.modalEditCache[key].edit = true;
        });
    }

    isEditableTd(id, index): boolean {
        return this.editCache[id].edit && index % 2 === 0 && index > 1;
    }

    isYearEditableTd(id, index): boolean {
        return this.yearEditCache[id].edit && index > 0;
    }

    reportTypeChanged(type): void {
        if (type === '3') {
            this.searchForm.removeControl('month');
            this.searchForm.removeControl('season');
        } else if (type === '1') {
            this.searchForm.removeControl('season');
            this.listOfControl = {
                id: 'month',
                controlInstance: 'month'
            };
            this.searchForm.addControl('month', new FormControl('4'));
        } else if (type === '2') {
            this.searchForm.removeControl('month');
            this.listOfControl = {
                id: 'season',
                controlInstance: 'season'
            };
            this.searchForm.addControl('season', new FormControl('夏秋灌'));
        }
        this.getGridData();
    }

    /**
     * 弹窗内筛选条件变化
     * @param type 3-年 2-灌季 1-月
     */
    reportModalTypeChanged(type): void {
        if (type === '3') {
            this.modalForm.removeControl('month');
            this.modalForm.removeControl('season');
        } else if (type === '1') {
            this.modalForm.removeControl('season');
            this.listOfModalControl = {
                id: 'month',
                controlInstance: 'month'
            };
            this.modalForm.addControl('month', new FormControl('4'));
        } else if (type === '2') {
            this.modalForm.removeControl('month');
            this.listOfModalControl = {
                id: 'season',
                controlInstance: 'season'
            };
            this.modalForm.addControl('season', new FormControl('夏秋灌'));
        }
        this.getModalGridData();
    }

    getGridData(): void {
        this.isUseWaterTableEditable = false;
        let queryParams = {};
        if (this.reportType === '1') {
            //  月度
            queryParams = {
                type: this.searchForm.value.type,
                time: `${this.searchForm.value.year}-${this.searchForm.value.month}`
            };
        } else if (this.reportType === '2') {
            //  灌季
            queryParams = {
                type: this.searchForm.value.type,
                time: `${this.searchForm.value.year}-${this.searchForm.value.season}`
            };
        } else if (this.reportType === '3') {
            //  年度
            queryParams = {
                type: this.searchForm.value.type,
                time: `${this.searchForm.value.year}`
            };
        }
        this.fetchService.post<any>('muw/wrsMuwWrData/list', queryParams).subscribe(res => {
            if (res && res.wrsMuwWrDatas.length) {
                const group = _.groupBy(res.wrsMuwWrDatas, 'classify');
                this.isGhMng = Object.keys(group).length > 1;
                const params = this.isGhMng ? this.radioValue : '';
                this.uploadUrl = `${(window as any).environment.apiBaseUrl}muw/wrsMuwMReport/import?classify=${params}`;
                let listData = [];
                if (this.isGhMng) {
                    listData = group[this.radioValue];
                } else {
                    listData = res.wrsMuwWrDatas;
                }
                this.resDataCache = res;
                this.areaHeadArr = listData.map(item => {
                    return item.trWrName;
                });
                //  合计
                const valArr0 = [];
                const totalValArr0 = [];
                //  农业
                const valArr = [];
                const totalValArr = [];
                //  工业
                const valArr1 = [];
                const totalValArr1 = [];
                //  生活
                const valArr2 = [];
                const totalValArr2 = [];
                //  生态
                const valArr3 = [];
                const totalValArr3 = [];
                //  区外供水
                const valArr4 = [];
                const totalValArr4 = [];
                listData.forEach(item => {
                    valArr0.push(item.currentTotal);
                    totalValArr0.push(item.total);
                    valArr.push(item.val);
                    totalValArr.push(item.valTotal);
                    valArr1.push(item.val1);
                    totalValArr1.push(item.val1Total);
                    valArr2.push(item.val2);
                    totalValArr2.push(item.val2Total);
                    valArr3.push(item.val3);
                    totalValArr3.push(item.val3Total);
                    valArr4.push(item.val4);
                    totalValArr4.push(item.val4Total);
                });
                const firstRow = {
                    id: 'val',
                    name: '本月'
                };
                const secondRow = {
                    id: 'valTotal',
                    name: '累计'
                };
                const firstRow1 = {
                    id: 'val1',
                    name: '本月'
                };
                const secondRow1 = {
                    id: 'val1Total',
                    name: '累计'
                };
                const firstRow2 = {
                    id: 'val2',
                    name: '本月'
                };
                const secondRow2 = {
                    id: 'val2Total',
                    name: '累计'
                };
                const firstRow3 = {
                    id: 'val3',
                    name: '本月'
                };
                const secondRow3 = {
                    id: 'val3Total',
                    name: '累计'
                };
                const firstRow4 = {
                    id: 'val4',
                    name: '本月'
                };
                const secondRow4 = {
                    id: 'val4Total',
                    name: '累计'
                };
                const firstRow0 = {
                    id: 'currentTotal',
                    name: '本月'
                };
                const secondRow0 = {
                    id: 'total',
                    name: '累计'
                };
                this.areaHeadArr.forEach((key, idx) => {
                    firstRow0[key] = valArr0[idx];
                    secondRow0[key] = totalValArr0[idx];
                    firstRow[key] = valArr[idx];
                    secondRow[key] = totalValArr[idx];
                    firstRow1[key] = valArr1[idx];
                    secondRow1[key] = totalValArr1[idx];
                    firstRow2[key] = valArr2[idx];
                    secondRow2[key] = totalValArr2[idx];
                    firstRow3[key] = valArr3[idx];
                    secondRow3[key] = totalValArr3[idx];
                    firstRow4[key] = valArr4[idx];
                    secondRow4[key] = totalValArr4[idx];
                });
                if (this.reportType === '1') {
                    this.areaTableData = [firstRow0, secondRow0, firstRow, secondRow, firstRow1, secondRow1, firstRow2, secondRow2, firstRow3, secondRow3, firstRow4, secondRow4];
                    this.updateEditCache();
                } else {
                    this.yearAreaTableData = [firstRow0, firstRow, firstRow1, firstRow2, firstRow3, firstRow4];
                    this.updateYearAreaEditCache();
                }
            }
            this.fetchService.post<any>('muw/wrsMuwMReport/list', queryParams).subscribe(r => {
                if (r) {
                    const tableGroup = _.groupBy(r, 'classify');
                    let tableData = [];
                    if (this.isGhMng) {
                        tableData = tableGroup[this.radioValue];
                    } else {
                        tableData = r;
                    }
                    this.monthlyTableData = tableData;
                    this.yearlyTableData = tableData;
                }
            });
        });
    }
    submitMainTableData(): void {
        this.modal.confirm({
            nzTitle: '确认提交并上报？',
            nzContent: '',
            nzOnOk: () => {
                const queryParams = {
                    type: this.reportType,
                    datas: this.reportType === '1' ? this.monthlyTableData : this.yearlyTableData
                };
                if (this.reportType === '1') {
                    //  月度
                    _.assign(queryParams, {
                        time: `${this.searchForm.value.year}-${this.searchForm.value.month}`
                    });
                } else if (this.reportType === '2') {
                    //  灌季
                    _.assign(queryParams, {
                        time: `${this.searchForm.value.year}-${this.searchForm.value.season}`
                    });
                } else if (this.reportType === '3') {
                    //  年度
                    _.assign(queryParams, {
                        time: `${this.searchForm.value.year}`
                    });
                }
                this.fetchService.post<any>('muw/wrsMuwMReport/add', queryParams).subscribe(r => {
                    // this.submit(2)
                    this.submit(2).then(() => {
                        this.message.success('提交成功');
                        this.getGridData();
                    });
                });
            }
        });
    }
    // submit(status: number): void {
    //     const table = _.cloneDeep(this.reportType === '1' ? this.areaTableData : this.yearAreaTableData);
    //     // const currData = table[0];
    //     const paramData = _.cloneDeep(this.resDataCache);
    //     table.forEach(currData => {
    //         _.forEach(currData, (val, key) => {
    //             const obj = _.find(paramData['wrsMuwWrDatas'], o => {
    //                 return o.trWrName === key;
    //             });
    //             if (obj) {
    //                 obj[currData.id] = val;
    //                 const index = _.findIndex(paramData['wrsMuwWrDatas'], o => {
    //                     return o['trWrName'] === key;
    //                 });
    //                 _.fill(paramData['wrsMuwWrDatas'], obj, index, index + 1);
    //             }
    //         });
    //     });
    //     console.log(table, paramData);
    //
    //     const data = _.assign(paramData, {statu: status, type: this.reportType});
    //     this.fetchService.post<any>('muw/wrsMuwWrData/add', data).subscribe(res => {
    //         const message = status === 1 ? '暂存成功' : '提交成功';
    //         this.message.success(message);
    //         this.getGridData();
    //     });
    // }
    // status: 1-暂存 2-提交
    submit(status: number): Promise<void> {
        return new Promise(resolve => {
            const table = _.cloneDeep(this.reportType === '1' ? this.areaTableData : this.yearAreaTableData);
            // const currData = table[0];
            const paramData = _.cloneDeep(this.resDataCache);
            table.forEach(currData => {
                _.forEach(currData, (val, key) => {
                    const obj = _.find(paramData['wrsMuwWrDatas'], o => {
                        return o.trWrName === key;
                    });
                    if (obj) {
                        obj[currData.id] = val;
                        const index = _.findIndex(paramData['wrsMuwWrDatas'], o => {
                            return o['trWrName'] === key;
                        });
                        _.fill(paramData['wrsMuwWrDatas'], obj, index, index + 1);
                    }
                });
            });
            console.log(table, paramData);

            const data = _.assign(paramData, {statu: status, type: this.reportType});
            this.fetchService.post<any>('muw/wrsMuwWrData/add', data).subscribe(res => {
                resolve();
                // const message = status === 1 ? '暂存成功' : '提交成功';
                // this.message.success(message);
                // this.getGridData();
            });
        });
    }

    openReportModal(): void {
        this.modalShow = true;
        this.getModalGridData();
    }

    /**
     * 填报弹窗内表格数据获取
     */
    getModalGridData(): void {
        let queryParams = {};
        if (this.modalReportType === '1') {
            //  月度
            queryParams = {
                type: this.modalForm.value.type,
                time: `${this.modalForm.value.year}-${this.modalForm.value.month}`
            };
        } else if (this.modalReportType === '2') {
            //  灌季
            queryParams = {
                type: this.modalForm.value.type,
                time: `${this.modalForm.value.year}-${this.modalForm.value.season}`
            };
        } else if (this.modalReportType === '3') {
            //  年度
            queryParams = {
                type: this.modalForm.value.type,
                time: `${this.modalForm.value.year}`
            };
        }
        this.fetchService.post<any>('muw/wrsMuwMReport/list', queryParams).subscribe(r => {
            if (r) {
                const tableGroup = _.groupBy(r, 'classify');
                let tableData = [];
                if (this.isGhMng) {
                    tableData = tableGroup[this.radioValue];
                } else {
                    tableData = r;
                }
                this.modalTableData = tableData;
                this.updateModalEditCache();
            }
        });
    }

    /**
     * 填报弹窗内表格数据提交
     */
    modalSubmit(): void {
        const queryParams = {
            type: this.modalReportType,
            datas: this.modalTableData
        };
        if (this.modalReportType === '1') {
            //  月度
            _.assign(queryParams, {
                time: `${this.modalForm.value.year}-${this.modalForm.value.month}`
            });
        } else if (this.modalReportType === '2') {
            //  灌季
            _.assign(queryParams, {
                time: `${this.modalForm.value.year}-${this.modalForm.value.season}`
            });
        } else if (this.modalReportType === '3') {
            //  年度
            _.assign(queryParams, {
                time: `${this.modalForm.value.year}`
            });
        }
        this.fetchService.post<any>('muw/wrsMuwMReport/add', queryParams).subscribe(r => {
            this.message.success('提交成功');
            this.getModalGridData();
        });
    }

    onCancel() {
        this.modalShow = false;
        this.getGridData();
    }

    downLoadExcel(): void {
        // window.location.href = `${(window as any).environment.apiBaseUrl}muw/wrsMuwMReport/export`;
        const params = this.isGhMng ? this.radioValue : '';
        this.http.get(`muw/wrsMuwMReport/export?type=${this.reportType}&classify=${params}`, {
            responseType: 'blob'
        }).subscribe(data => {
            const file = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
            const link = document.createElement('a');
            link.id = 'tempId';
            document.body.appendChild(link);
            link.style.display = 'none';
            link.download = '月度报表上报数据模板';
            link.href = URL.createObjectURL(file);
            link.click();
            const tempA = document.getElementById('tempId');
            if (tempA) {
                tempA.parentNode.removeChild(tempA);
            }
        });
    }

    customReq = (item: UploadXHRArgs) => {
        const formData = new FormData();
        let currTime;
        if (this.reportType === '1') {
            //  月度
            currTime = `${this.searchForm.value.year}-${this.searchForm.value.month}`;
        } else if (this.reportType === '2') {
            //  灌季
            currTime = `${this.searchForm.value.year}-${this.searchForm.value.season}`;
        } else if (this.reportType === '3') {
            //  年度
            currTime = this.searchForm.value.year;
        }
        formData.append('file', item.file as any);
        formData.append('time', currTime);
        formData.append('type', this.reportType);
        // this.uploading = true;
        // this.fetchService.post(item.action!, formData).subscribe(res => {
        //     this.message.success('上传成功');
        // });
        const req = new HttpRequest('POST', item.action!, formData, {
            reportProgress: true,
            withCredentials: false
        });
        return this.http.request(req).subscribe(
            (event: HttpEvent<{}>) => {
                if (event.type === HttpEventType.UploadProgress) {
                    if (event.total! > 0) {
                        // tslint:disable-next-line:no-any
                        (event as any).percent = (event.loaded / event.total!) * 100;
                    }
                    item.onProgress!(event, item.file!);
                } else if (event instanceof HttpResponse) {
                    item.onSuccess!(event.body, item.file!, event);
                    if (event.body['error']) {
                        this.message.error(`上传失败，原因：'${event.body['error'].msg}'；`);
                    } else {
                        this.message.success('数据上传成功');
                    }
                    this.getGridData();
                }
            },
            err => {
                item.onError!(err, item.file!);
                this.message.error('上传失败，请重新上传');
            }
        );
    }
}
